#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <cstdio>

#include "log.hpp"

const int size = 4096;

#define Pathname "/home/hhb01"
#define proj_id 0x6666

Log log;

key_t Getkey()
{
  key_t k = ftok(Pathname, proj_id);
  if (k < 0)
  {
    log(Fatal, "ftok create failed, error: %s", strerror(errno));
    exit(1);
  }
  log(Info, "ftok create success, key: %d", k);
  return k;
}

int GetSharememHelper(int flag)
{
  key_t key = Getkey(); // 让操作系统生成key
  // 让操作系统开辟一块共享内存空间
  int shmid = shmget(key, size, flag);
  if (shmid < 0)
  {
    log(Fatal, "shmget is failed, error: %s", strerror(errno));
    exit(2);
  }
  log(Info, "shmget is successful, shmid: %d", shmid);

  return shmid;
}

int createShm()
{
  return GetSharememHelper(IPC_CREAT | IPC_EXCL | 0666);
}

int getShm()
{
  return GetSharememHelper(IPC_CREAT);
}